package iterator;

import global.AttrType;
import global.RID;
import heap.Heapfile;
import heap.Scan;
import heap.Tuple;
import heap.exceptions.InvalidTupleSizeException;
import heap.exceptions.InvalidTypeException;
import index.exceptions.IndexException;
import iterator.exceptions.FileScanException;
import iterator.exceptions.JoinsException;
import iterator.exceptions.LowMemException;
import iterator.exceptions.PredEvalException;
import iterator.exceptions.SortException;
import iterator.exceptions.TupleUtilsException;
import iterator.exceptions.UnknowAttrType;
import iterator.exceptions.UnknownKeyTypeException;

import java.io.IOException;

import bufmgr.exceptions.PageNotReadException;

public class FileScan extends Iterator {
	/**
	 * @uml.property name="_in1"
	 * @uml.associationEnd multiplicity="(0 -1)"
	 */
	private AttrType[] _in1;
	private short[] s_sizes;
	private Heapfile f;
	private Scan scan;
	private Tuple tuple1;

	public FileScan(String file_name, AttrType in1[], short s1_sizes[],
			FldSpec[] proj_list, CondExpr[] outFilter) throws FileScanException {

		_in1 = in1;
		s_sizes = s1_sizes;
		tuple1 = new Tuple();

		try {
			tuple1.setHdr(_in1, s1_sizes);
		} catch (Exception e) {
			throw new FileScanException(e, "setHdr() failed");
		}
		tuple1.size();

		try {
			f = new Heapfile(file_name);

		} catch (Exception e) {
			throw new FileScanException(e, "Create new heapfile failed");
		}

		try {
			scan = f.openScan();
		} catch (Exception e) {
			throw new FileScanException(e, "openScan() failed");
		}

	}

	@Override
	public Tuple get_next() throws IOException, JoinsException, IndexException,
			InvalidTupleSizeException, InvalidTypeException,
			PageNotReadException, TupleUtilsException, PredEvalException,
			SortException, LowMemException, UnknowAttrType,
			UnknownKeyTypeException, Exception {
		// create start rid
		RID rid = new RID();

		// get next from heap file
		tuple1 = scan.getNext(rid);

		if (tuple1 == null) {
			return null;
		}
		// set header with types and attr sizes
		tuple1.setHdr(_in1, s_sizes);
		return tuple1;

		// TODO Auto-generated method stub

	}

	@Override
	public void close() throws IOException, JoinsException, SortException,
			IndexException {
		scan.closescan();

	}

}
